package com.qf.efserver.alarm.service.Impl;

import com.qf.common.core.entity.SleepSchedule;
import com.qf.common.xxljob.core.XxlJobInfo;
import com.qf.common.xxljob.utils.XxlJobUtil;
import com.qf.efserver.alarm.param.AlarmParam;
import com.qf.efserver.alarm.service.AlarmService;
import com.qf.efserver.alarm.service.SleepScheduleService;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AlarmServiceImpl implements AlarmService {

    @Resource
    private SleepScheduleService sleepScheduleService;

    @Resource
    private XxlJobUtil xxlJobUtil;

    @Override
    public void addAlarm(AlarmParam alarmParam) {
        LocalTime remindTime = LocalTime.parse(alarmParam.getRemindTime());
//        表示cron表达式类型和提醒时间
        String cronExpression = xxlJobUtil.generateCronExpression(remindTime, alarmParam.getRepeatType());


        SleepSchedule sleepSchedule = new SleepSchedule();
        sleepSchedule.setCorn(cronExpression);
        sleepSchedule.setStartDate(alarmParam.getStartDate());
        sleepSchedule.setEndDate(alarmParam.getEndDate());
        sleepSchedule.setStatus(1);

        sleepScheduleService.save(sleepSchedule);
//看是否在当天
        List<String> recentTimes = xxlJobUtil.getRecentDataByCorn(cronExpression, 1, new Date());
        if (!recentTimes.isEmpty() && LocalDateTime.parse(recentTimes.get(0)).toLocalDate().isEqual(LocalDate.now())) {
            // 添加定时任务
            XxlJobInfo xxlJobInfo = new XxlJobInfo();
            xxlJobInfo.setTriggerStatus(0);
            xxlJobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");
            xxlJobInfo.setAuthor("admin小军");
            xxlJobInfo.setScheduleConf(sleepSchedule.getCorn());
            xxlJobInfo.setExecutorRouteStrategy("FIRST");
            xxlJobInfo.setTriggerStatus(0);
            xxlJobInfo.setJobDesc("提醒睡觉");
            xxlJobInfo.setMisfireStrategy("DO_NOTHING");
            xxlJobInfo.setScheduleType("CRON");
            xxlJobInfo.setGlueType("BEAN");
            xxlJobInfo.setExecutorHandler("alarmTask");
            xxlJobInfo.setExecutorFailRetryCount(0);
            xxlJobInfo.setId(sleepSchedule.getId());
            xxlJobInfo.setExecutorTimeout(0);

            xxlJobUtil.addAndStart(xxlJobInfo);
            System.out.println("定时任务添加成功");
        }
    }


}

